package com.gcloud.mesh.framework.core;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class SpringUtil implements ApplicationContextAware {
	
	 private static ApplicationContext APPLICATION_CONTEXT;

	    @Override
	    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	        log.info("[SpringUtil] 初始化中。。。。");
	        if (SpringUtil.APPLICATION_CONTEXT == null) {
	            SpringUtil.APPLICATION_CONTEXT = applicationContext;
	        }
	    }

	    public static <T> T getBeanOfType(Class<T> clazz, String name) {
	        return APPLICATION_CONTEXT.getBean(name, clazz);
	    }

	    public static <T> Map<String, T> getBeansOfType(Class<T> beanType) {
	        return APPLICATION_CONTEXT.getBeansOfType(beanType);
	    }

	    public static <T> List<T> getBeanListOfType(Class<T> beanType) {
	        return Lists.newArrayList(APPLICATION_CONTEXT.getBeansOfType(beanType).values());
	    }

	    public static String getEnvProperty(String key) {
	        return APPLICATION_CONTEXT.getEnvironment().getProperty(key);
	    }


	    //获取applicationContext
	    public static ApplicationContext getApplicationContext() {
	        return APPLICATION_CONTEXT;
	    }

	    //通过name获取 Bean.
	    public static Object getBean(String name){
	        return getApplicationContext().getBean(name);
	    }

	    //通过class获取Bean.
	    public static <T> T getBean(Class<T> clazz){
	        return getApplicationContext().getBean(clazz);
	    }

	    //通过class获取Bean列表.
	    public static <T> Collection<T> getBeans(Class<T> clazz) {
	        return getApplicationContext().getBeansOfType(clazz).values();
	    }

	    //通过name,以及Clazz返回指定的Bean
	    public static <T> T getBean(String name,Class<T> clazz){
	        return getApplicationContext().getBean(name, clazz);
	    }
}
